import style from '.module.less'
import { defineComponent, nextTick, onMounted, ref } from 'vue'

export default defineComponent({
    setup: () => {
        const pointerWidth = 60
        const pointerProcess = 20

        const pointerProcessAvailableOffset = pointerWidth - pointerProcess
        const domRef = ref<HTMLDivElement>()
        const pointerProcessOffset = ref(0)

        let viewProcessAvailableOffset = 0

        const syncProcess = (scrollLeft: number) => {
            const percentProcess = scrollLeft / viewProcessAvailableOffset
            pointerProcessOffset.value = pointerProcessAvailableOffset * percentProcess
        }

        const initScrollListener = () => {
            const { previousSibling } = domRef.value || {}
            if (!previousSibling) return

            const { scrollWidth, clientWidth } = previousSibling as HTMLDivElement
            viewProcessAvailableOffset = scrollWidth - clientWidth

            previousSibling.addEventListener('scroll', () => syncProcess((previousSibling as HTMLDivElement).scrollLeft))
        }
        onMounted(() => { nextTick(initScrollListener) })
        return () => <div ref={domRef} class={style.root}
            style={`width:${pointerWidth}px;--pointerProcess:${pointerProcess}px;--pointerProcessOffset:${pointerProcessOffset.value}px`} />
    }
})